package com.ganlucode.sipmock.utils;

import com.ganlucode.sipmock.config.SipConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sip.*;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;

/**
 * @author GanLu
 * @date 2020-05-15 15:11
 */
@Slf4j
@Component
public class SipHelper {

    @Value("${sip.client.transport}")
    private String transport;

    @Autowired
    @Qualifier("tcpSipProvider")
    private SipProvider tcpSipProvider;

    @Autowired
    @Qualifier("udpSipProvider")
    private SipProvider udpSipProvider;


    public ServerTransaction createServerTransaction(RequestEvent evt) {
        Request request = evt.getRequest();
        ServerTransaction serverTransaction = evt.getServerTransaction();
        ViaHeader reqViaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
        if (serverTransaction == null) {
            try {
                if (isTcp(reqViaHeader.getTransport())) {
                    serverTransaction = tcpSipProvider.getNewServerTransaction(request);
                } else {
                    serverTransaction = udpSipProvider.getNewServerTransaction(request);
                }
            } catch (TransactionAlreadyExistsException | TransactionUnavailableException e) {
                log.error("获取事务失败",e);
            }
        }
        return serverTransaction;
    }

    /**
     * 判端是TCP还是UDP
     * @param transport
     * @return
     */
    public boolean isTcp(String transport) {
        if (SipConfiguration.TRANSPORT_TCP.equalsIgnoreCase(transport)) {
            return true;
        }
        return false;
    }


    public String getTransport() {

        return isTcp(transport) ? SipConfiguration.TRANSPORT_TCP : SipConfiguration.TRANSPORT_UDP;
    }


    public SipProvider getSipProvider() {

        return isTcp(transport) ? tcpSipProvider : udpSipProvider;
    }

}
